$(function () {
	
		//选择节点
		$('#comboxNode').combobox({
			url: BASE_URL_KETTLE_SLAVE_SERVER_CRUD +'?v=' + Date.parse(new Date()),
			editable: false,
			valueField: 'id',
			textField: 'name',
			method:'get',
			//data:"level=2",
			onSelect: function(record) {
				$("#comboxNode").val(record.id);
				search();
				//console.log(record);
			},
			loadFilter:function(data){
				return data._embedded.kettleSlaveServers;
			},
			onLoadSuccess: function() {
				var data = $("#comboxNode").combobox("getData");
				if(data && data.length > 0)
				{
					var defaultId = $("#comboxNode").combobox("getData")[0].id;
					$("#comboxNode").combobox("select",defaultId);
					//search();  
				}
				
			}
		});
});

function search() {
	var nodeId = $('#comboxNode').combobox("getValue");
	if(!nodeId)
	{
		return;
	}
	setNodeInfo(null);
	if($('#chart').highcharts())
	{
		$('#chart').highcharts().destroy();
	}
	
	getNodeInfo(nodeId);
	getTwelveHourAgoTime(nodeId);
}

function getNodeInfo(nodeId) {
	if(!nodeId)
	{
		return;
	}
	$.ajax({
		url:BASE_URL_SLAVE_SERVER_STATISTICS_SEARCH +"/countByNodeIdAndTime?nodeId=" + nodeId + "&v=" + Date.parse(new Date()),
		type:'get',
		contentType:"application/json",
		success:function(data){	
			if(data && data.content)
			{
				setNodeInfo(data.content[0]);
			}
		},
		error: function() {
			$.messager.alert('错误','<p>服务异常，查询节点信息失败，请稍后重试!</p>','error');
		}
	});
}

function setNodeInfo(nodeInfo) {
	if(nodeInfo)
	{
		$("#name").html(nodeInfo.name);
		$("#hostName").html(nodeInfo.hostName);
		//$("#port").html(nodeInfo.port);
		$("#type").html(nodeInfo.isMaster? "主服务器":"从服务器");
		$("#allRunTimes").html(nodeInfo.allRunTimes);
		$("#errorRate").html(nodeInfo.errorRate.replace("%", ""));
		$("#mostRunTimes").html(nodeInfo.mostRunTimes);
		
		var errorRate = parseFloat($("#errorRate").html());
		var correctRate = 100 - errorRate;
		var errorChartData = [{
				name:'错误率',
				y:errorRate,
				color: '#fe8080'
			},
            {
				name:'正常率',
				y:correctRate,
				color:'#ffc65c'
			}];
		if($('#chart2').highcharts())
		{
			$('#chart2').highcharts().destroy();
		}
		drawErrorRateChart(errorChartData);
	}
	else
	{
		$("#name").html("");
		$("#hostName").html("");
		//$("#port").html("");
		$("#type").html("");
		$("#allRunTimes").html("");
		$("#errorRate").html("");
		$("#mostRunTimes").html("");
		
		if($('#chart2').highcharts())
		{
			$('#chart2').highcharts().destroy();
		}
	}
}

function getTwelveHourAgoTime(nodeId) {
	if(!nodeId)
	{
		return;
	}
	$.ajax({
		url:BASE_URL_SLAVE_SERVER_STATISTICS_SEARCH +"/findTwelveHourAgoTime?nodeId=" + nodeId + "&v=" + Date.parse(new Date()),
		type:'get',
		contentType:"application/json",
		success:function(data){
			if(data && data.content)
			{
				var chartData = {categories:[], data:[]};
				for(var i = 0; i < data.content.length; ++i)
				{
					var dataY = parseFloat(data.content[i].runTime);
					chartData.categories.push(data.content[i].runEndTime.split(" ")[1]);
					chartData.data.push({
						y:dataY/*data.content[i].runTime*/
					});
				}
				if($('#chart').highcharts())
				{
					$('#chart').highcharts().destroy();
				}
				drawElapsedTimeChart(chartData);
			}
		},
		error: function() {
			$.messager.alert('错误','<p>服务异常，查询节点信息失败，请稍后重试!</p>','error');
		}
	});
}

function drawElapsedTimeChart(data) {
	var average = 0;
	var sum = 0;
	var len = data.data.length;
	for(var i = 0; i　< len; ++i)
	{
		sum += data.data[i].y;
	}
	if(len > 0)
	{
		//average = Math.round(sum/len);
		average = (sum/len).toFixed(2);
	}
	
	$('#chart').highcharts({
        chart: {
            type: 'spline'
        },
        title: {
            text: '平均耗时',
            x: 0 //center
        },
        subtitle: {
            text: '平均值：' + average + '(秒)',
            x: 0
        },
		credits: {
			enabled: false
		},
	    legend: {
	    	enabled: false
	    },
        xAxis: {
        	type:"datetime",
			categories: data.categories,
			//maxZoom: 14 * 24 * 3600000, // fourteen days
			title: {
				text: null
			},			
			gridLineWidth:1,
			gridLineDashStyle:'Dash'
        },
        yAxis: {
            title: {
                text: '耗时(秒)'
            },
            min: 0,
			gridLineDashStyle:'Dash'
        },
        tooltip: {
            formatter: function() {
                    return '<b>耗时：</b>'+
                    this.y + '秒';
            }
			
        },
        
        series: [{
            name: '',
            data: data.data
        }]
    });
}

function drawErrorRateChart(data) {

	$('#chart2').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
        },
        title: {
            text: '错误率'
        },
        tooltip: {
    	    pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>'
        },
		credits: {
			enabled: false
		},
		legend: {
	    	enabled: true,
	    	align: 'right',
	    	verticalAlign: 'top',
	    	layout: 'vertical',
	    	floating: true,
	    	itemStyle: {
	    		fontWeight: 'normal'
	    	},
	    	labelFormat: '<p">{name}</p>'
	    	/*labelFormatter: function(){
	    		var textColor = this.name == "按时"? '#fe8080':'#32d6c5';
	    		return '<p style="color:' + textColor + ';">' + this.name + '</p>';
	    	}*/
	    },
        plotOptions: {
            pie: {
                allowPointSelect: false,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    color: '#000000',
                    connectorColor: '#000000',
                    format: '<b>{point.name}</b>: {point.percentage:.2f} %'
                }
            }
        },
        series: [{
			showInLegend: true,
            type: 'pie',
            name: '节点运行情况',
            data: data
        }]
    });
}